import React, { useEffect, useState } from 'react';
import { Button, Cascader, Flex, Form, Input, Modal, Pagination, Select, Table, message } from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
import type { UserInfo, UserSearchParams } from '@/apis/userInfo/type';
import { getUserInfo } from '@/apis/userInfo/user';
import AddUser from '@/components/user/AddUser';

type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];


const IMG_URL = import.meta.env.VITE_IMG_URL;



const UserInfoApp: React.FC = () => {

  const [usertypes, setUsertypes] = useState([
    { id: 2, name: '租户' }
    , { id: 1, name: '业主' }
  ]);

  const [buildings, setBuildings] = useState([
    {
        "id": 1,
        "name": "昌茂花园",
        "pid": 0,
        "leaf":0,
        "children": [
            {
                "id": 3,
                "name": "1栋",
                "pid": 1,
                "leaf":1,
                "children": []
            },
            {
                "id": 4,
                "name": "2栋",
                "pid": 1,
                "leaf":1,
                "children": []
            }
        ]
    },
    {
        "id": 2,
        "name": "清水湾",
        "pid": 0,
        "leaf":1,
        "children": []
    }
]);

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const [loading, setLoading] = useState(false);

  const [editUser,setEditUser]=useState<UserInfo | null>();

  const [params, setParams] = useState<UserSearchParams>({ psize: 10, page: 1 });

  const [dataSource, setDataSource] = useState<UserInfo[]>([]);
  const [total, setTotal] = useState(0); //总记录数

  const handlePageChange = (page: number, psize: number) => {

    setParams({ ...params, psize, page });


  }
  useEffect(() => {
    getData();

  }, [params]);
  const getData = async () => {

    console.log("调接口");

    const res = await getUserInfo(params).catch(() => undefined);
    if (!res) return;

    setDataSource(res.list);
    setTotal(res.counts);




  }

  // useEffect(() => {
  //   getData();
  // }, [])

  const handleDel = async (id: number) => {

    
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条数据吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {

        console.log("删除", id);
        
        
      },
    });
  }
  const handleEdit = (data: UserInfo) => {

    setEditUser(data);
     console.log(data);
     setIsModalOpen(true);
  }


  const columns: TableColumnsType<UserInfo> =
    [
      { title: 'id', width: 60, dataIndex: 'id' },
      {
        title: '头像', dataIndex: 'photo', render: (data) => (<>
          <img style={{ height: 50 }} src={IMG_URL + data} alt="" />
        </>)
      },
      { title: '姓名', dataIndex: 'name' },
      { title: '类型', dataIndex: 'usertypeName' },
      { title: '房间号', dataIndex: 'houseno' },

      { title: '电话', dataIndex: 'mobile' },
      {
        title: '操作', width: 100, dataIndex: 'id', render: (_, record) => (<>

          <Flex gap="5px"> <Button onClick={() => handleDel(record.id)} type="primary" danger>
            删除
          </Button>
            <Button onClick={() => handleEdit(record)} type="primary">
              修改
            </Button></Flex>

        </>)
      },
    ];


  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection: TableRowSelection<UserInfo> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const handleDelete = () => {

    if(selectedRowKeys.length === 0) return  message.error("请选择要删除的行");

    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条数据吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {

        console.log("删除", selectedRowKeys);
        
        
      },
    });


  

  }
  const onFinish = (values: UserSearchParams) => {
 

    let buildingid=values.buildingids ? values.buildingids[values.buildingids.length-1] : 0;

    setParams({ ...params, ...values, page: 1,buildingid });


  }

  // const buildingChange=(values:number[])=>{

  //   let buildingid=values ? values[values.length-1] : 0;

  //   setParams({ ...params, buildingid });
    

  // }
  const [isModalOpen, setIsModalOpen] = useState(false);
  const handleAdd=()=>{
    setEditUser(null);
    setIsModalOpen(true);
  }

  const closeHandle=()=>{
    console.log("父组件接收到的数据");

    setIsModalOpen(false);
    
  }

  return (
    <Flex gap="middle" vertical>
      <Form name="horizontal_login" layout="inline" onFinish={onFinish}>

      <Form.Item<UserSearchParams> label="楼栋" name="buildingids">
          <Cascader fieldNames={{ label:'name',value: 'id' }} options={buildings}  placeholder="请选择楼栋" />
        </Form.Item>


        <Form.Item<UserSearchParams> label="姓名" name="name">
          <Input style={{width:150}} allowClear placeholder="请输入姓名" />
        </Form.Item>
        <Form.Item<UserSearchParams> label="电话" name="mobile">
          <Input style={{width:150}} allowClear placeholder="请输入电话" />
        </Form.Item>
        <Form.Item<UserSearchParams> label="房间号" name="houseno">
          <Input style={{width:150}}  allowClear placeholder="请输入房间号" />
        </Form.Item>
        <Form.Item<UserSearchParams> name="usertype" label="居民类型">
          <Select
          allowClear
           placeholder="请选择居民类型"
            style={{ width: 150 }}
            options={usertypes}
            fieldNames={{ label: "name", value: "id" }}
          />
        </Form.Item>
        <Button htmlType="submit" type="primary">
          搜索
        </Button>
      </Form>
      <Flex  gap="5px">
        <Button onClick={handleDelete} type="primary" danger>
          删除
        </Button>
        <Button onClick={handleAdd} type="primary">
          添加
        </Button>
      </Flex>
      <Table<UserInfo> rowKey="id" rowSelection={rowSelection} pagination={false} columns={columns} dataSource={dataSource} />
      <Flex justify='center'>
        <Pagination
          onChange={handlePageChange}
          total={total}
          pageSize={params.psize}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `总 ${total} 条`}
        />
      </Flex>
      {
        isModalOpen &&  <AddUser data={editUser} close={closeHandle}></AddUser>
      }
    
    </Flex>
  );
};

export default UserInfoApp;